package org.uni_hi.lsep.gui;

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.net.MalformedURLException;

import javax.swing.JTree;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeSelectionModel;
import javax.swing.tree.TreeSelectionModel;

import org.uni_hi.lsep.AppManager;
import org.uni_hi.lsep.text.ChapterNode;
import org.xml.sax.SAXException;

public class NavigationTree extends JTree implements Runnable{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public NavigationTree() throws NullPointerException {
		super(new DefaultMutableTreeNode(new ChapterNode(new java.io.File("data/1.html").toURI())));
		init();
	}

	private void init(){
		//create the displayed tree
		createNodes((DefaultMutableTreeNode) this.getModel().getRoot());

		// # config the tree
		// expands the first row, the root node
		this.expandRow(0);
		// hides the root
		this.setRootVisible(false);
		// disables nodes to be dragged and dropped
		this.setDragEnabled(false);
		// expands nodes at first click, standard is two
		this.setToggleClickCount(1);
		// changes the selection mode for the tree, so only one row can be selected
		DefaultTreeSelectionModel dtsm=new DefaultTreeSelectionModel();
		dtsm.setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
		this.setSelectionModel(dtsm);
		//sets the renderer for this tree
		this.setCellRenderer(new NavigationTreeCellRenderer());
		//sets the row height for each item
		this.setRowHeight(20);
		
		// as one node is selected the corresponding content will be loaded in the HtmlPanel   
		this.addTreeSelectionListener(new TreeSelectionListener() {
			@Override
			public void valueChanged(TreeSelectionEvent e) {
				ChapterNode cn=null;
				try {
					DefaultMutableTreeNode dmtn=((DefaultMutableTreeNode) e.getNewLeadSelectionPath().getLastPathComponent());
					cn=((ChapterNode) dmtn.getUserObject());
					AppManager.getBrowser().setPage(cn.getURL());
					AppManager.getMainFrame().getNavigationbar().setTitle(dmtn.getUserObject().toString());
					AppManager.getMainFrame().getNavigationbar().setForwardLink(dmtn.getNextNode());
					AppManager.getMainFrame().getNavigationbar().setBackwardLink(dmtn.getPreviousNode().equals(dmtn.getRoot())?null:dmtn.getPreviousNode());
				} catch (MalformedURLException e1) {
					e1.printStackTrace();
				} catch (IllegalArgumentException e2){
					
				}
			}
		});
	}

	private void createNodes(DefaultMutableTreeNode top){
		String n=null,title=null;
		org.w3c.dom.Document doc=null;
		int l=0,index=-1;
		String[] chapters=null;
		DefaultMutableTreeNode curNode=null;
		java.io.File[] list=new java.io.File("data/").listFiles(new FilenameFilter(){
			@Override
			public boolean accept(File dir, String name) {
				int lio=name.lastIndexOf('.');
				if(lio>0 && name.substring(lio+1).equalsIgnoreCase("html")){
					return true;
				}else{
					return false;
				}
			}
		});

		for(File f:list){											// for every file in the list-Array
			n=f.getName(); 											// first get the filename
			l=n.lastIndexOf('.'); 									// then find the file type dot
			n=n.substring(0,l);										// create a string without the file type ending and dot
			chapters=n.split("[.]");

			curNode=top;

			for(String chap:chapters){

				try {
					index=Integer.parseInt(chap)-1;			// convert the chapter to
					try {
						while(curNode.getChildCount()<=index){
							curNode.add(new DefaultMutableTreeNode("temp"));
						}						
						curNode=(DefaultMutableTreeNode) curNode.getChildAt(index);
					} catch (ArrayIndexOutOfBoundsException e) {
					}
				} catch (NumberFormatException e1) {
					index=-1;
				}
			}

			if(index!=-1){
				title="Not defined";
				try {
					doc=AppManager.getBrowser().getDocumentforURI(f.toURI());
					title=""+n+" - "+AppManager.getBrowser().getTitleForDoc(doc);
					curNode.setUserObject(new ChapterNode(f.toURI(),title,AppManager.getBrowser().isRequestedPageTest(doc),AppManager.getBrowser().getNodeTypeForPage(doc)));
				} catch (SAXException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	@Override
	public void run() {

	}
}
